﻿using System;
using System.Threading.Tasks;
using System.Windows;
using WPFServices.Commands;
using WPFServices.Models.Domain;
using WPFServices.Services.DomainService.Role;

namespace WPFServices.ViewModels.DomainViewModel
{
    public class AddRoleViewModel : BaseViewModel
    {
        private readonly RoleService _roleService;
        private string _roleName = string.Empty;
        private string _description = string.Empty;

        public AddRoleViewModel()
        {
            _roleService = new RoleService();
            SaveCommand = new RelayCommand(async _ => await SaveRoleAsync(), _ => CanSave());
            CancelCommand = new RelayCommand(_ => Cancel());
        }

        public event Action<bool> CloseWindow;

        #region 属性
        public string RoleName
        {
            get => _roleName;
            set => SetProperty(ref _roleName, value);
        }

        public string Description
        {
            get => _description;
            set => SetProperty(ref _description, value);
        }
        #endregion

        #region 命令
        public RelayCommand SaveCommand { get; }
        public RelayCommand CancelCommand { get; }
        #endregion

        #region 方法
        private bool CanSave()
        {
            return !string.IsNullOrWhiteSpace(RoleName);
        }

        private async Task SaveRoleAsync()
        {
            try
            {
                var createDto = new CreateUpdateRoleDto
                {
                    RoleName = RoleName.Trim(),
                    Description = Description?.Trim()
                };

                // 调用RoleService的CreateRoleAsync方法
                var result = await _roleService.CreateRoleAsync(createDto);

                MessageBox.Show("角色创建成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                CloseWindow?.Invoke(true); // 返回true表示成功
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建角色失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Cancel()
        {
            CloseWindow?.Invoke(false); // 返回false表示取消
        }
        #endregion
    }
}